package cn.com.infcn.monitor.task.system;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;

import org.apache.log4j.Logger;
import org.hyperic.sigar.SigarException;

import cn.com.infcn.monitor.bean.IFCDirectory;
import cn.com.infcn.monitor.task.BaseTask;
import cn.com.infcn.monitor.util.IFCMonitorUtils;

/**
 * 获取指定目录的元数据信息
 * 
 * @author jjs
 *
 */
public class DirectoryTask implements BaseTask {

	private static final Logger LOGGER = Logger.getLogger(DirectoryTask.class);

	private String dirPath = null;

	public DirectoryTask(String dirPath) {
		this.dirPath = dirPath;
	}

	@Override
	public IFCDirectory execute() throws Exception {
		return directory();
	}

	private IFCDirectory directory() throws SigarException {

		try {
			IFCDirectory dir = new IFCDirectory();
			dir.setDirPath(dirPath);
			File f = new File(dirPath);
			// 判断文件路径是否正确
			if (f.exists()) {
				dir.setIsExists(1); // 是否存在
				dir.setIsHidden(IFCMonitorUtils.convertInt(f.isHidden())); // 是否隐藏文件
				Path filePath = Paths.get(dirPath); // 文件路径
				BasicFileAttributes ra = Files.readAttributes(filePath, BasicFileAttributes.class);
				dir.setCreateDate(ra.creationTime().toMillis()); // 文件创建时间
				dir.setLastAccessTime(ra.lastAccessTime().toMillis()); // 最后访问时间
				dir.setSize(ra.size()); // 文件大小
				dir.setLastModifiedTime(ra.lastModifiedTime().toMillis()); // 最后修改时间
				dir.setIsSymbolicLink(IFCMonitorUtils.convertInt(ra.isSymbolicLink())); //
				dir.setIsDirectory(IFCMonitorUtils.convertInt(ra.isDirectory())); //
				dir.setIsRegularFile(IFCMonitorUtils.convertInt(ra.isRegularFile())); //
			} else {
				dir.setIsExists(0);
			}
			return dir;
		} catch (Exception e) {
			LOGGER.warn(e.getMessage(), e);
		}

		return null;
	}
}
